package com.example.war;

import java.io.IOException;
import java.io.InputStream;

import javax.microedition.khronos.opengles.GL10;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.opengl.GLUtils;
import android.util.DisplayMetrics;
import android.view.WindowManager;

public class Utils {
	private static final String TAG ="Utils";

	public static Bitmap loadRawImage(Resources res, int resId) {
    	InputStream is = res.openRawResource(resId);
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(is);
        } finally {
            try {
                is.close();
            } catch(IOException e) {
            }
        }

        return bitmap;
    }

	public static void buildMipmap(GL10 gl, Bitmap bitmap) {
		int level = 0;
		int height = bitmap.getHeight();
		int width = bitmap.getWidth();

		while(height >= 1 || width >= 1) {
			//First of all, generate the texture from our bitmap and set it to the according level
			GLUtils.texImage2D(GL10.GL_TEXTURE_2D, level, bitmap, 0);
			
			if(height == 1 || width == 1) {
				break;
			}

			//Increase the mipmap level
			level++;

			height /= 2;
			width /= 2;
			Bitmap bitmap2 = Bitmap.createScaledBitmap(bitmap, width, height, true);
			
			//Clean up
			bitmap.recycle();
			bitmap = bitmap2;
		}
	}
	
	public static int nextPow2(int value) {
		int retVal = 1;
		while(retVal < value) retVal<<=1;
		return retVal;
	}
	
	public static Point getScreenSize(Context context) {
	    DisplayMetrics metric = new DisplayMetrics();
	    ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(metric);
	    //return new Point(480, 800);
        return new Point(metric.widthPixels, metric.heightPixels);
	}
}
